package Java基础.线程池;

import java.util.concurrent.*;

/**
 * 异常处理：
 * 1、try-catch
 * 2、Thread.setUncaughtExceptionHandler
 * 3、ThreadFactory中设置默认的异常处理
 * 4、重写 afterExecute方法
 *
 */
public class T05_异常处理 {

    public static void main(String[] args) {
        // 创建一个固定大小的线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3,
                1000,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(10));


        // 提交任务到线程池
        for (int i = 0; i < 5; i++) {
            final int taskId = i;

            Thread thread = new Thread(() -> {
                if (taskId == 3) {
                    // 模拟任务抛出异常
                    throw new RuntimeException("Task " + taskId + " failed with an exception");
                } else {
                    // 正常任务执行
                    System.out.println("Task " + taskId + " executed successfully");
                }
            });
            thread.setUncaughtExceptionHandler((t, e) -> {
                // 处理异常
                System.err.println("Thread " + t.getName() + " threw an uncaught exception: " + e.getMessage());
            });

            executor.execute(thread);
        }

        // 关闭线程池
        executor.shutdown();
    }

}
